<?php


namespace app\admin\controller;

use app\admin\validate\IDMustBePositiveInt;
use app\admin\validate\ConfigValidate;
use app\service\model\ConfigModel;
use app\service\Y;
use think\Request;

class Config extends BaseAdmin
{

    /**
     * 配置列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(Request $request): \think\response\Json
    {
        $data = ConfigModel::paginate([
            'list_rows'=> input('param.limit', 10),
            'query' => input('param.')
        ])->toArray();
        return Y::table($data['data'], $data['total']);
    }

    /**
     * 创建、编辑配置
     * @param Request $request
     * @param ConfigValidate $config_validate
     * @return \think\response\Json
     * @throws \app\service\exception\ParameterException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(Request $request, ConfigValidate $config_validate): \think\response\Json
    {
        $id = input('param.id', 0);

        if ($request->isPost()) {
            $config_validate->goCheck();
            $param = $config_validate->getDataByRule();

            $param['remark'] = input('param.remark', '');
            $param['options_desc'] = input('param.options_desc', '');

            return ConfigModel::saveData($param, $id);
        }

        $data = [];
        if ($id > 0) {
            $data = ConfigModel::find($id);
        }
        return Y::success($data, '配置数据');
    }

    /**
     * 删除数据
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(IDMustBePositiveInt $IDMustBePositiveInt): \think\response\Json
    {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id');
        return $this->deleteDate((new ConfigModel()), $id);
    }
}